package com.mindainfo.groundwave.server.device.service;

import com.alibaba.fastjson.JSON;
import com.mindainfo.groundwave.common.api.device.service.IEventReportService;
import com.mindainfo.groundwave.common.api.device.vo.EventReportVo;
import com.mindainfo.groundwave.common.bean.CommonResult;
import com.mindainfo.groundwave.common.bean.ResultFactory;
import com.mindainfo.groundwave.server.device.bean.DeviceOperate;
import com.mindainfo.groundwave.server.device.bean.EventReport;
import com.mindainfo.groundwave.server.device.dao.IEventReportDao;
import com.mindainfo.groundwave.server.device.mapper.EventReportMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by MD-01 on 2017/6/13.
 */
@Service
@Transactional
public class EventReportServiceImpl implements IEventReportService{

    private Logger logger = LoggerFactory.getLogger("设备事件");

//    @Resource
//    private IEventReportDao reportDao;

    @Resource
    private EventReportMapper reportMapper;

    @Override
    public CommonResult<List<EventReportVo>> queryEvent() {

        logger.info("获取开门事件");

        Date queryDate = DateUtils.addSeconds(new Date(), -60);
        //Date queryDate = DateUtils.addHours(new Date(), -5);
        List<EventReport> eventReports = reportMapper.query(queryDate,0);
        logger.info(JSON.toJSONString(eventReports));

        List<EventReportVo> vos = new ArrayList<>();
        List<Integer> idList = new ArrayList<>();
        if(eventReports.size()>0){
            for(EventReport report: eventReports){

                idList.add(report.getId());

                EventReportVo vo = new EventReportVo();
                vo.setDoorId(report.getDoorId());
                if(report.getEvent().equals("门关")){
                    vo.setAction(0);
                }else{
                    vo.setAction(1);
                }
                vos.add(vo);
            }
            //ids = ids.substring(1);
            reportMapper.updateReport(idList);
        }
        if(vos.size()>0){
            logger.info(JSON.toJSONString(vos));
        }

        return ResultFactory.ok(vos);
    }

}
